<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OAuth Example</title>
    <style>

        button {
            line-height: 40px;
            border: 1px solid #685;
            border-radius: 3px;
            margin: 20px;
        }

        a {
            margin: 10px;
        }

    </style>
</head>

<body>
    <h1>Hello OAuth</h1>

    
    <nav>
        <a href="/hello">hello</a>
        <a href="/index.html">home</a>
        <a href="/index2.html">home2</a>
    </nav>

    <button onclick="goAuth()">gitee go auth page get code</button>
    <button onclick="refreshToken()">gitee refresh token</button>

    <script>
        var redirect_uri = sessionStorage.redirect_uri || ''
        function goAuth() {

            // 在gitee注册的应用id 和设置的回调地址 （用户点击授权按钮后，gitee会回调该地址并传入code参数)
            // 回调地址可注册多个
            const client_id = '0cfd6ea020f6d1ec304388f77026dd368acef37996162c9c259c60f528b03891'
            // redirect_uri = 'http://localhost:3000/not-this-login' // 若输入的回调地址不是注册的那个，则gitee授权页会提示错误 "无效的登录回调地址"
            redirect_uri = 'http://localhost:3000/login' // 地址正确，授权页， 列出即将授予的权限列表，可点击【同意授权】按钮 完成授权
            // redirect_uri = 'http://localhost:3000/index.html' // 回调地址也可以配置为前端页面  gitee授权页授权后，返回到 http://localhost:3000/index.html?code=38c651b8a5000fc94ff76d353d7dec3b7f9ca0a3862a4002e60833da0709a178
            sessionStorage.redirect_uri = redirect_uri

            // 2:: 若回调地址是后端接口
            // 应用登录页 -- oauth授权页 -- 应用后端接口 -- http get token -- setCookie token,  前端获取不到 refreshToken 需要后端保存到session

            const url = `https://gitee.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code`

            location.href = url;
        }


        function refreshToken() {
            fetch('/refreshTokenByBackend', {
                method: 'POST',
                headers: { // 需要设置 application/json  express.json中间件才能把请求体解析到req.body
                    'content-type': 'application/json'
                },
                body: JSON.stringify({})
            })
            .then(res => res.json())
            .then(res => {
                if (res.success) {
                    alert('success refresh token')
                } else {
                    alert(res.msg);
                }
                console.log("🚀 ~ file: index.html:65 ~ refreshToken ~ res:", res)
            })
        }


    </script>
</body>

</html>